/**
 * 通用操作
 */

let COMMON = {};
let DEBUG = false;
let TIME_OUT = 3000;

COMMON.debug = DEBUG;

/**
 * 消息提示
 */
COMMON.Log = msg => {
  console.log(msg);
  if (COMMON.debug)
    toast(msg); // 以气泡显示信息
}

//-------------------------------------------------------------------------------
//                              点击
//-------------------------------------------------------------------------------
/**
 * 点击坐标
 */
COMMON.Click = (x, y) => {
  click(x, y);
}

/**
 * 点击区域
 */
COMMON.ClickBounds = (x1, y1, x2, y2) => {
  x = x1 + (x2 - x1) / 2;
  y = y1 + (y2 - y1) / 2;
  click(x, y);
}

/**
 * 按照转换后的坐标点点击
 * x: 按照自己手机屏幕获取的点击点的x坐标
 * y: 按照自己手机屏幕获取的点击点的y坐标
 */
COMMON.ClickByRatio = (x, y) => {
  let _x = parseInt(x / 1080 * device.width);
  let _y = parseInt(y / 2160 * device.height);
  click(_x, _y);
}

/**
 * 点击控件所在坐标
 */
COMMON.ClickButton = btn => {
  if (btn) {
    click(btn.bounds().centerX(), btn.bounds().centerY());
  }
}

/**
 * 按文本查找按钮并点击
 */
COMMON.ClickByText = txt => {
  const btn = text(txt).findOne(TIME_OUT);
  if (!btn) {
    COMMON.Log('没找到‘' + txt + '’按钮')
    return false;
  }
  COMMON.Log('找到了‘' + txt + '’按钮');
  COMMON.ClickButton(btn);
  return true;
}

/**
 * 按文本正则匹配按钮并点击
 */
COMMON.ClickByMatchesText = reg => {
  const btn = textMatches(reg).findOne(TIME_OUT);
  if (!btn) {
    COMMON.Log('没匹配到‘' + reg + '’按钮');
    return false;
  }
  COMMON.Log('匹配到了‘' + reg + '’按钮');
  COMMON.ClickButton(btn);
  return true;
}

/**
 * 按desc文本查找按钮并点击
 */
COMMON.ClickByDesc = txt => {
  const btn = desc(txt).findOne(TIME_OUT);
  if (!btn) {
    COMMON.Log('没找到‘' + txt + '’按钮');
    return false;
  }
  COMMON.Log('找到了‘' + txt + '’按钮');
  COMMON.ClickButton(btn);
  return true;
}

/**
 * 按desc文本正则匹配按钮并点击
 */
COMMON.ClickByMatchesText = reg => {
  const btn = descMatches(reg).findOne(TIME_OUT);
  if (!btn) {
    COMMON.Log('没匹配到‘' + reg + '’按钮');
    return false;
  }
  COMMON.Log('匹配到了‘' + reg + '’按钮');
  COMMON.ClickButton(btn);
  return true;
}

/**
 * 按id文本查找按钮并点击
 */
COMMON.ClickById = sid => {
  const btn = id(sid).findOne(TIME_OUT);
  if (!btn) {
    COMMON.Log('没找到‘' + sid + '’按钮');
    return false;
  }
  COMMON.Log('找到了‘' + sid + '’按钮');
  COMMON.ClickButton(btn);
  return true;
}

/**
 * 按文本包含内容查找按钮并点击
 */
COMMON.ClickByTextContains = txt => {
  const btn = textContains(txt).findOne(TIME_OUT);
  if (!btn) {
    COMMON.Log('没找到‘' + txt + '’按钮');
    return false;
  }
  COMMON.Log('找到了‘' + txt + '’按钮');
  COMMON.ClickButton(btn);
  return true;
}

//-------------------------------------------------------------------------------
//                              滑动
//-------------------------------------------------------------------------------
/**
 * 模拟从坐标(x1, y1)滑动到坐标(x2, y2)
 */
COMMON.Swipe = (x1, y1, x2, y2, duration) => {
  swipe(x1, y1, x2, y2, duration);
}

COMMON.SwipeUp = () => {
  swipe(device.width / 2, device.height * 0.8, device.width / 2, device.height * 0.5, 500);
}

COMMON.SwipeDown = () => {
  swipe(device.width / 2, device.height * 0.5, device.width / 2, device.height * 0.9, 500);
}

COMMON.SwipeLeft = () => {
  swipe(device.width * 0.8, device.height / 2, device.width * 0.3, device.height / 2, 500);
}

COMMON.SwipeRight = () => {
  swipe(device.width * 0.3, device.height / 2, device.width * 0.8, device.height / 2, 500);
}

/**
 * 随机滑动
 */
COMMON.RandomSwipe = () => {
  smoothMove(ramdomByFloat(device.width / 2), ramdomByFloat(device.height / 1.5), ramdomByFloat(device.width / 2), ramdomByFloat(device.height / 4), ramdomByFloat(800));
}

function ramdomByFloat(number) {
  return random(number, number);
}

function random(min, max) {
  return Math.round(Math.random() * (max - min)) + min;
}

function smoothMove(qx, qy, zx, zy, time) {
  let xxy = [time];
  let point = [];
  let dx0 = {
    "x": qx,
    "y": qy
  };
  let dx1 = {
    "x": random(qx - 100, qx + 100),
    "y": random(qy, qy + 50)
  };
  let dx2 = {
    "x": random(zx - 100, zx + 100),
    "y": random(zy, zy + 50),
  };
  let dx3 = {
    "x": zx,
    "y": zy
  };
  for (let i = 0; i < 4; i++) {
    eval("point.push(dx" + i + ")");
  };
  for (let i = 0; i < 1; i += 0.08) {
    xxyy = [parseInt(bezierCurves(point, i).x), parseInt(bezierCurves(point, i).y)];
    xxy.push(xxyy);
  }
  gesture.apply(null, xxy);
}

function bezierCurves(cp, t) {
  cx = 3.0 * (cp[1].x - cp[0].x);
  bx = 3.0 * (cp[2].x - cp[1].x) - cx;
  ax = cp[3].x - cp[0].x - cx - bx;
  cy = 3.0 * (cp[1].y - cp[0].y);
  by = 3.0 * (cp[2].y - cp[1].y) - cy;
  ay = cp[3].y - cp[0].y - cy - by;

  tSquared = t * t;
  tCubed = tSquared * t;
  result = {
    "x": 0,
    "y": 0
  };
  result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
  result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
  return result;
}

//-------------------------------------------------------------------------------
//                              识图
//-------------------------------------------------------------------------------
/**
 * 截屏查找图片颜色并单击对应的点
 * @param {number} num 重试次数
 * @param {string} rgb 颜色值 ‘#112233’
 * @param {number} xr 区域坐标 起点x 小数时，是按照屏幕长宽按照给定的值按照比例动态算出的坐标
 * @param {number} yr 区域坐标 起点y
 * @param {number} wr 区域坐标 宽
 * @param {number} hr 区域坐标 高
 * @param {boolean} flipup 反转屏幕
 * @returns 
 */
COMMON.ClickByColor = (num, rgb, xr, yr, wr, hr, flipup) => {
  while (num--) {
    let img = captureScreen();
    if (flipup != undefined)
      img = images.rotate(img, 180);
    if (xr < 1)
      var region = [
        parseInt(img.getWidth() * xr),
        parseInt(img.getHeight() * yr),
        parseInt(img.getWidth() * wr),
        parseInt(img.getHeight() * hr)
      ];
    else
      var region = [
        xr, yr, wr, hr
      ];
    let point = findColor(img, rgb,
      {
        region: region,
        threshold: 8
      });
    if (point) {
      if (flipup != undefined) {
        point.x = img.getWidth() - point.x;
        point.y = img.getHeight() - point.y;
      }
      return click(point.x, point.y);
    }
    if (num) sleep(1000);
  }
  return false;
}

/**
 * 在屏幕上匹配图片并点击
 */
COMMON.ClickByImages = (num, imgFile, flipup, color, region, threshold) => {
  let templ = images.read(imgFile);
  if (color == undefined)
    templ = images.grayscale(templ);
  while (num--) {
    let img = captureScreen();
    if (flipup != undefined)
      img = images.rotate(img, 180);
    if (color == undefined)
      img = images.grayscale(img);
    if (threshold != undefined)
      threshold = 0.9;
    else
      threshold = threshold;
    if (region != undefined)
      var point = findImage(img, templ, {
        threshold: threshold, //图片相似度
        region: region
      });
    else
      var point = findImage(img, templ, {
        threshold: threshold //图片相似度
      });

    if (point) {
      if (flipup != undefined) {
        point.x = img.getWidth() - point.x; point.y = img.getHeight() - point.y;
      }
      COMMON.Log('找到了‘' + imgFile + '’图片');
      return click(point.x, point.y);
    }
    if (num)
      sleep(1000);
  }
  COMMON.Log('没找到‘' + imgFile + '’图片');
  return false;
}

module.exports = COMMON;
